package com.jiyun.result.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;

/**
 * @author diChenLin
 * @date 2024/5/1
 * @email 576658449@163.com
 * @description JWT工具类
 */
public class JwtUtil {
    // 密钥
    private static final String SECRET = "dichenlin";
    // 过期时间(毫秒)
    private static final long EXPIRE_TIME = 7 * 24 * 60 * 60 * 1000;
    // 缓存时间(毫秒)
    private static final long CACHE_TIME = 1 * 24 * 60 * 60 * 1000;
    // 刷新时间(毫秒)
    private static final long REFRESH_TIME = 1 * 24 * 60 * 60 * 1000;


    /**
     * 根据OpenId生成Token
     */
    public static String createToken(String userId) {
        try {
            Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            // 附带username信息
            return JWT.create()
                    .withClaim("userId", userId)
                    //到期时间
                    .withExpiresAt(date)
                    //创建一个新的JWT，并使用给定的算法进行标记
                    .sign(algorithm);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 根据OpenId刷新Token
     */
    public static String refreshToken(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            Date expiresAt = jwt.getExpiresAt();
            //如果过期时间已经到了需要刷新的时候
            if (expiresAt.getTime() - System.currentTimeMillis() > REFRESH_TIME) {
                String userId = getUserId(token);
                return createToken(userId);
            }
            return token;
        } catch (JWTDecodeException e) {
            return null;
        }
    }


    /**
     * 校验 token 是否正确
     */
    public static boolean verifyToken(String token, String openId) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            //在token中附带了username信息
            JWTVerifier verifier = JWT.require(algorithm)
                    .withClaim("userId", openId)
                    .build();
            //验证 token
            verifier.verify(token);
            return true;
        } catch (Exception exception) {
            return false;
        }
    }


    /**
     * 获得token中的信息，无需secret解密也能获得
     */
    public static String getUserId(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("userId").asString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }
}
